<template>
	<view class="appointment">
		<u-subsection mode="subsection" :list="list" keyName="name" :current="current" @change="handleFormTypeChange">
		</u-subsection>
		<view class="tips">
			<view class="tips-title">说明</view>
			<view class="tips-content">{{explain}}</view>
		</view>
		<view class="appointment-type">
			<u-radio-group :value="appointmentType" @change="handleAppointmentTypeChange">
				<u-radio v-for="type in appointmentTypeList" :key="type.key" :customStyle="{marginRight: '16px'}"
					:label="type.name" :name="type.value">
				</u-radio>
			</u-radio-group>
		</view>
		<view class="appointment-form">
			<u-form ref="uForm" :model="form" :errorType="errorType" labelPosition="top" labelWidth="100">
				<u-form-item label="姓名" prop="name">
					<u-input prefixIcon="account-fill" prefixIconStyle="font-size: 22px;color: #C1C1C1"
						placeholder="请输联系人姓名" v-model="form.name" />
				</u-form-item>
				<u-form-item label="手机号码" prop="phone">
					<u-input prefixIcon="phone-fill" prefixIconStyle="font-size: 22px;color: #C1C1C1"
						placeholder="请输联系人电话" v-model="form.phone" />
				</u-form-item>
				<u-form-item v-if="isHome" label="地址" prop="address">
					<u-input prefixIcon="map" prefixIconStyle="font-size: 22px;color: #C1C1C1" placeholder="请输入您的地址"
						v-model="form.address" />
				</u-form-item>
				<u-form-item v-if="isAssessmentForm" label="品牌车型" prop="brand">
					<u-input prefixIcon="car-fill" prefixIconStyle="font-size: 22px;color: #C1C1C1"
						placeholder="例：丰田卡罗拉" v-model="form.brand" />
				</u-form-item>
				<u-form-item v-if="isAssessmentForm" label="行驶里程" prop="mileage">
					<u-radio-group v-model="form.mileage">
						<u-radio v-for="(item, index) in mileageList" :key="index" :customStyle="{marginRight: '16px'}"
							:label="item.name" :name="item.name">
						</u-radio>
					</u-radio-group>
				</u-form-item>
				<u-form-item label="车辆种类" prop="car_type_id" borderBottom @click="showCarType = true; hideKeyboard()">
					<u--input v-model="currentCarType" disabled disabledColor="#ffffff" placeholder="请选择车辆种类"
						border="none">
					</u--input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>
				<u-form-item :label="timeLabel" prop="time" borderBottom @click="showTime = true; hideKeyboard()">
					<u--input v-model="form.time" disabled disabledColor="#ffffff" :placeholder="timePlaceholder"
						border="none">
					</u--input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>
			</u-form>
		</view>
		<u-action-sheet :show="showCarType" :actions="carTypeList" title="请选择车辆种类" @close="showCarType = false"
			@select="carTypeSelect">
		</u-action-sheet>
		<u-datetime-picker :show="showTime" :value="time" mode="datetime" closeOnClickOverlay @confirm="timeConfirm"
			:filter="timeFilter" @cancel="timeClose" @change="handleTimeChange" @close="timeClose" ref="datetimePicker"
			:minDate="minDate"></u-datetime-picker>
		<u-button :customStyle="submitBtn" type="primary" @click="submit">提交</u-button>
	</view>
</template>

<script>

	import FormTypeEnum from '@/common/enum/FormType.js'
	import AppointmentTypeEnum from '@/common/enum/AppointmentType.js'
	import * as Api from '@/api/appointment.js'
	import * as CarTypeApi from '@/api/carType.js'

	export default {
		data() {
			return {
				minDate: new Date().getTime(),
				submitBtn: {
					marginTop: '100rpx'
				},
				list: FormTypeEnum.getData().map(item => item.name),
				// 当前表单类型索引
				current: 0,
				// 最小小时
				minHour: 0,
				// 最大小时
				maxHour: 0,
				// 预约说明
				explain: '',
				form: {
					name: '',
					phone: '',
					address: '',
					brand: '',
					mileage: '1-3万',
					car_type_id: '',
					time: '',
				},
				errorType: 'message',
				rules: {
					name: [{
						required: true,
						message: '请输入姓名',
						trigger: ['blur', 'change']
					}],
					phone: [{
						required: true,
						message: '请填写手机号码',
						trigger: ['blur', 'change']
					}, {
						validator: (rule, value, callback) => {
							// 返回true表示校验通过，返回false表示不通过
							return uni.$u.test.mobile(value);
						},
						message: '手机号码不正确',
						// 触发器可以同时用blur和change
						trigger: ['blur', 'change'],
					}],
					car_type_id: [{
						validator: (rule, value, callback) => {
							return !uni.$u.test.isEmpty(value)
						},
						message: '请选择车辆类型',
						trigger: ['blur', 'change']
					}],
					time: [{
						required: true,
						message: '请选择时间',
						trigger: ['blur', 'change']
					}],
					address: [{
						validator: (rule, value, callback) => {
							// 若当前预约类型为上门，验证地址字段
							if (this.isHome) {
								return !uni.$u.test.isEmpty(value)
							}

							return true
						},
						message: '请填写地址',
						trigger: ['blur', 'change'],
					}],
					brand: [{
						validator: (rule, value, callback) => {
							// 若当前表单类型为免费评估，验证品牌字段
							if (this.isAssessmentForm) {
								return !uni.$u.test.isEmpty(value)
							}

							return true
						},
						message: '请填写品牌车型',
						trigger: ['blur', 'change'],
					}],
				},
				showCarType: false,
				// 车辆种类列表
				carTypeList: [],
				// 当前选择的车辆种类名字
				currentCarType: '',
				showTime: false,
				// 默认时间
				time: Number(new Date()),
				// 当前预约类型, store 到店，home 上门
				appointmentType: AppointmentTypeEnum.STORE.value,
				// 里程列表
				mileageList: [{
					name: '1-3万'
				}, {
					name: '3-5万'
				}, {
					name: '5-10万'
				}, {
					name: '10万以上'
				}]
			};
		},
		computed: {
			timeLabel() {
				return this.isHome ? '上门时间' : '到店时间'
			},

			timePlaceholder() {
				return this.isHome ? '请选择上门时间' : '请选择到店时间'
			},

			appointmentTypeList() {
				return AppointmentTypeEnum.getData()
			},

			// 是否预约上门
			isHome() {
				return this.appointmentType === AppointmentTypeEnum.HOME.value
			},

			// 是否评估表单
			isAssessmentForm() {
				return FormTypeEnum.getData()[this.current].value === FormTypeEnum.ASSESSMENT.value
			}
		},

		onLoad() {
			// 获取车辆种类列表
			this.getCarTypeList()
			// 获取预约设置
			this.getSetting()
		},
		
		mounted() {
			console.log('mounted: ', this,this.$refs, this.$refs.uForm)
		},

		onReady() {
			console.log('onReady: ', this, this.$refs, this.$refs.uForm)
			this.$refs.uForm.setRules(this.rules)
			this.$refs.datetimePicker.setFormatter(this.formatter)
		},
		methods: {
			// 获取预约设置
			getSetting() {
				Api.setting().then(res => {
					console.log(res)
					const { explain } = res.setting
					this.explain = explain
					// this.minHour = startTime.split(':')[0]
				})
			},
			// 获取车辆种类列表
			getCarTypeList() {
				CarTypeApi.list().then(res => {
					this.carTypeList = res.list
				})
			},

			timeFilter(mode, options) {
				// console.log(mode, options)

				return options;
			},

			formatter(type, value) {
				if (type === 'year') {
					return `${value}年`
				}
				if (type === 'month') {
					return `${value}月`
				}
				if (type === 'day') {
					return `${value}日`
				}
				if (type === 'hour') {
					return `${value}时`
				}
				if (type === 'minute') {
					return `${value}分`
				}
				return value
			},

			// 切换预约类型
			handleAppointmentTypeChange(type) {
				this.appointmentType = type
			},

			// 切换表单类型
			handleFormTypeChange(index) {
				this.current = index;
			},

			carTypeSelect(e) {
				this.form.car_type_id = e.car_type_id
				this.currentCarType = e.name
				this.$refs.uForm.validateField('form.car_type_id')
			},

			hideKeyboard() {
				uni.hideKeyboard()
			},

			timeClose() {
				this.showTime = false
				this.$refs.uForm.validateField('form.time')
			},

			timeConfirm(e) {
				this.showTime = false
				this.time = e.value
				this.form.time = uni.$u.timeFormat(e.value, 'yyyy-mm-dd hh:MM')
				this.$refs.uForm.validateField('form.time')
			},

			handleTimeChange(e) {

			},

			// 提交表单
			submit() {
				// 验证表单
				this.$refs.uForm.validate().then(res => {
					// 验证成功，添加表单类型和预约类型参数
					const form = {
						...this.form,
						appointment_type: this.appointmentType,
						form_type: FormTypeEnum.getData()[this.current].value
					}
					// 获取用户微信code
					wx.login({
						success: res => {
							console.log(res)
							form.code = res.code
							console.log(form)
							Api.submit({
								form
							}).then(res => {
								console.log(res)
								// 提交成功，跳转到首页
								uni.showModal({
									title: '提交成功',
									showCancel: false,
									success: res => {
										if (res.confirm) {
											uni.redirectTo({
												url: '/pages/index/index'
											})
										}
									}
								});
							})
						}
					})
				}).catch(errors => {
					// 验证失败
				})
			}
		}
	}
</script>

<style scoped lang="scss">
	.appointment {
		box-sizing: border-box;
		padding: 45.56rpx 28.03rpx;
		font-family: 'PingFangSC-Regular';

		.tips {
			margin-top: 28.03rpx;

			.tips-title {
				font-size: 16px;
				margin-bottom: 8.76rpx;
			}

			.tips-content {
				font-size: 14px;
				color: #7F7F7F;
			}
		}

		.appointment-type {
			width: 62%;
			margin: 0 auto;
			margin-top: 32rpx;

			/deep/ .u-radio-group--row {
				justify-content: space-between;
			}

			/deep/ .u-radio {
				margin-right: 0 !important;
			}

		}

		.appointment-form {
			margin-top: 31.54rpx;

			/deep/ .u-form-item__body__right__message {
				margin-left: 0 !important;
			}
		}
	}
</style>
